package com.ylr.mqtest;

import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author ylr
 * @version 1.0.0
 * @ClassName Consumer.java
 * @Description TODO
 * @createTime 2022年03月18日 18:02:00
 */
@Service
public class Consumer {
    private static final Logger log = LoggerFactory.getLogger(Consumer.class);
    public static final CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList();

    public Consumer() {
    }

    @RabbitListener(
            bindings = {@QueueBinding(
                    value = @Queue(
                            value = "mqtestq",
                            durable = "true"
                    ),
                    exchange = @Exchange(
                            value = "mqtest",
                            type = "direct",
                            ignoreDeclarationExceptions = "true"
                    ),
                    key = {"mqtest"}
            )}
    )
    @RabbitHandler
    public void onMessage(Message message, Channel channel) {
        System.out.println(message.getMessageProperties().toString());
        String msg = new String(message.getBody());
        log.info("监听到的消息是： 【{}】", msg);

        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException var6) {
            log.error("手动ack错误，消息内容：【{}】", msg, var6);
            var6.printStackTrace();
        }

        try {
            log.info("开始处理消息");
            if (StringUtils.hasLength(msg)) {
                log.info("处理消息内容：{}", msg);
                if (list.size() > 10) {
                    list.clear();
                }

                list.add(msg);
                log.info("处理完毕！");
            }
        } catch (Exception var5) {
            log.error("处理消息内容逻辑错误，消息内容：【{}】", var5.getMessage());
            var5.printStackTrace();
        }

    }
}

